/*
 * @Author: blak-kong
 * @Date: 2019-12-10 12:57:42
 * @Email: 546598185@qq.com
 */


// models
const About = require('../models/About');
const News = require('../models/News');
const { SuccessModel, ErrorModel } = require("../models/resModel")


module.exports = {
    async uccn (ctx, next) {
        let aboutDocs = await About.find({})
        let res = aboutDocs[0]
        let introduce = res.content
        let contact = {
            "name": res.name,
            "address": res.address,
            "phone": res.phone,
            "email": res.email
        }

        let options = {
            skip: 0, // 跳过零
            limit: 5, // 取五条
            sort:{"create_time":"-1"}
        }
        let newDocs = await News.find({},null,options);

        ctx.body = new SuccessModel({
            introduce: introduce,
            contact: contact,
            news: newDocs
        }, "获取成功!")
    },
    async query (ctx, next) {
        let docs = await About.find({})
        let res = docs[0]
        if (res.id) {
            ctx.body = new SuccessModel(res, "获取成功!")
            return
        }
        ctx.body = new ErrorModel({}, "服务器错误！")
    },
    
    async update (ctx, next) {
        // let markdowne = new Markdown(ctx.request.body)
        let docs = await About.find({});
        let doc = docs[0]
        doc.name = ctx.request.body.name
        doc.address = ctx.request.body.address
        doc.phone = ctx.request.body.phone
        doc.email = ctx.request.body.email
        doc.content = ctx.request.body.content
        
        let res = await doc.save()
        if (res.id) {
            ctx.body = new SuccessModel({}, "更新成功！")
            return
        }
        ctx.body = new ErrorModel({}, "更新失败！请稍后重试！")
    },


    async add (ctx, next) {
        // save() 需要先给model赋值实例化
        let doc = new About(ctx.request.body)
        let res = await doc.save()
        if (res.id) {
            ctx.body = new SuccessModel({}, "创建成功！")
            return
        }
        ctx.body = new ErrorModel({}, "创建失败！请稍后重试！")
    },
}